package com.conversationboard.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.controller.confirm.Confirm;
import com.conversationboard.security.EncryptionException;

@WebServlet(name = "AdminConfirmDeleteSelectedThreadsControllerServlet", urlPatterns = "/Admin/AdminConfirmDeleteSelectedThreadsControllerServlet")
public class AdminConfirmDeleteSelectedThreadsControllerServlet extends HttpServlet {

	private static final long serialVersionUID = 3615946147267540470L;


	/** Make some hidden tags to go into a form */

	private String generateTags(int boardId, int threadId, String loginId, String[] messageIDs) throws EncryptionException, IOException {

		StringBuilder buffer = new StringBuilder();

		buffer.append("<input name='boardId' value='" + boardId + "' type='hidden' />");
		buffer.append("<input name='threadId' value='" + threadId + "' type='hidden' />");

		/* type='checkbox' */

		for (String messageId : messageIDs) {
			buffer.append("<input name='checkbox' value='" + messageId + "' type='hidden'>");
		}

		buffer.append(Confirm.getKey(loginId));

		return buffer.toString();

	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		try {
			int boardId = Integer.parseInt(request.getParameter("boardId"));
			int threadId = Integer.parseInt(request.getParameter("threadId"));
			String[] messageIDs = request.getParameterValues("checkbox");

			String loginId = request.getUserPrincipal().getName();

			String tags = this.generateTags(boardId, threadId, loginId, messageIDs);

			request.setAttribute("tags", tags);

			RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/Admin/confirmmultipledelete.jsp");
			dispatcher.forward(request, response);

		} catch (NumberFormatException e) {
			throw new ServletException(e);
		} catch (EncryptionException e) {
			throw new ServletException(e);
		}

	}

}
